<template>
  <el-dialog
    :title="editFlag ? '编辑规则' : '新增规则'"
    class="addDialog"
    :visible.sync="dialogVisible1"
    :before-close="handleClose"
    :close-on-click-modal="false"
    width="55%"
  >
    <el-form
      ref="addform"
      :model="vpnform"
      :rules="rulesVpnform"
      label-width="110px"
    >
      <el-form-item label="关联场景:" prop="sceneId">
        <el-select
          v-model="vpnform.sceneId"
          @change="getsceneType"
          :disabled="scene"
        >
          <el-option
            v-for="item in sceneList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="规则名称:" prop="ruleName">
        <el-input
          v-model="vpnform.ruleName"
          maxlength="256"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <template v-if="sceneType == 2">
        <el-form-item label="风险属性:" prop="riskField">
          <el-select v-model="vpnform.riskField" @change="handlechange">
            <el-option
              v-for="item in riskFieldList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则类型:" prop="ruleType">
          <el-select v-model="vpnform.ruleType">
            <el-option
              v-for="item in ruleTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 规则类型为区间时才会展示周期和次数和属性值区间 -->
        <template v-if="vpnform.ruleType === '1'">
          <el-form-item label="频率周期:" prop="cycleVal" key="cycleVal2">
            <el-select v-model="vpnform.cycleVal">
              <el-option
                v-for="item in cycleValList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="次数阈值:"
            prop="thresholdVal"
            key="thresholdVal2"
          >
            <el-input
              v-model="vpnform.thresholdVal"
              maxlength="256"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="vpnform.riskField === '0'"
            class="range"
            label="属性值区间:"
            prop="startIp"
            key="startIp"
          >
            <div style="display: flex; width: 100%">
              <el-input
                v-model="vpnform.startIp"
                maxlength="256"
                placeholder="请输入"
              ></el-input>
              ~
              <el-input
                v-model="endIp"
                ref="endIp"
                maxlength="256"
                placeholder="请输入"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item
            v-if="vpnform.riskField === '1'"
            class="range"
            label="属性值区间:"
            prop="intervalVal"
            key="intervalVal"
          >
            <div style="width: 100%">
              <el-time-picker
                is-range
                class="timepicker"
                v-model="vpnform.intervalVal"
                value-format="HH:mm:ss"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
              >
              </el-time-picker>
            </div>
          </el-form-item>
        </template>
      </template>
      <template v-else-if="sceneType == 1">
        <el-form-item label="频率周期:" prop="cycleVal" key="cycleVal1">
          <el-select v-model="vpnform.cycleVal">
            <el-option
              v-for="item in realcycleValList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="次数阈值:" prop="thresholdVal" key="thresholdVal1">
          <el-input
            v-model="vpnform.thresholdVal"
            maxlength="256"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </template>
      <el-form-item class="slider" label="扣分分值:" prop="deductVal">
        <el-slider v-model="vpnform.deductVal" :min="0" :max="100"></el-slider>
      </el-form-item>
      <el-form-item class="slider" label="风险系数:" prop="ruleRatio ">
        <el-slider
          v-model="vpnform.ruleRatio"
          :min="0"
          :max="100"
          :format-tooltip="formatTooltip"
        ></el-slider>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitaddForm('addform')"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import { mapState, mapActions } from "vuex";
import { addList, editList } from "@/api/yybl/riskRule";
export default {
  name: "rule",
  components: {},
  props: {
    dialogVisible1: {
      type: Boolean,
      default: false,
    },
    editFlag: {
      type: Boolean,
      default: false,
    },
    scene: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateIps = (rule, value, callback) => {
      let endIp = this.$refs.endIp.value;
      const isIP = (val) => {
        const regex =
          /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
        return regex.test(val);
      };
      function compareIPv4(ip1, ip2) {
        // 将IPv4地址从点分十进制的格式转换为32位的整数
        function ipToInt(ip) {
          const octets = ip.split(".");
          return (
            octets[0] * 256 ** 3 +
            octets[1] * 256 ** 2 +
            octets[2] * 256 +
            octets[3]
          );
        }
        const int1 = ipToInt(ip1);
        const int2 = ipToInt(ip2);
        if (int1 < int2) {
          return -1;
        } else if (int1 > int2) {
          return 1;
        } else {
          return 0;
        }
      }
      if (!isIP(value) || !isIP(endIp)) {
        callback(new Error("请输入正确格式的IP"));
      } else if (compareIPv4(value, endIp) === 1) {
        callback(new Error(`结束IP应该不小于开始IP`));
      } else {
        callback();
      }
    };
    return {
      startIp: "",
      endIp: "",
      sceneType: "",
      ruleTypeList: [
        // {
        //   label: "完全匹配",
        //   value: "0",
        // },
        {
          label: "频次匹配",
          value: "1",
        },
        // {
        //   label: "区间匹配",
        //   value: "2",
        // },
      ],
      vpnform: {},
      rulesVpnform: {
        sceneId: [
          { required: true, message: "请选择风险场景", trigger: "change" },
        ],
        ruleName: [
          { required: true, message: "请输入规则名称", trigger: "blur" },
        ],
        riskField: [
          { required: true, message: "请选择风险属性", trigger: "change" },
        ],
        ruleType: [
          { required: true, message: "请选择规则类型", trigger: "change" },
        ],
        cycleVal: [
          { required: true, message: "请选择频率周期", trigger: "change" },
        ],
        thresholdVal: [
          { required: true, message: "请输入次数阙值", trigger: "blur" },
        ],
        intervalVal: [
          { required: true, message: "请选择属性值区间", trigger: "change" },
        ],
        startIp: [
          // { required: true, message: "请选择属性值区间", trigger: "change" },
          { required: true, validator: validateIps, trigger: "blur" },
        ],
      },
    };
  },
  watch: {},
  computed: {
    ...mapState("common", ["sceneList", "riskFieldList", "cycleValList",'realcycleValList']),
  },
  methods: {
    ...mapActions("common", ["getsceneList"]),
    formatTooltip(val) {
      return val / 100;
      // return `${val}%`;
    },
    handlechange(val) {
      console.log(val);
      this.$refs?.addform?.clearValidate(["intervalVal", "startIp"]);
      // this.$nextTick(() => {
      //   if (val === "1") {
      //     this.$refs?.addform?.clearValidate(["startIp"]);
      //   } else if (val === "0") {
      //     this.$refs?.addform?.clearValidate(["intervalVal"]);
      //   } else {
      //     this.$refs?.addform?.clearValidate(["intervalVal", "startIp"]);
      //   }
      // });
    },
    getsceneType(val) {
      console.log(val, this.sceneList);
      if (this.sceneList.findIndex((i) => i.value == val) != -1) {
        this.sceneType =
          this.sceneList[
            this.sceneList.findIndex((i) => i.value == val)
          ].sceneType;
      }
    },
    add(sceneId) {
      this.vpnform = {
        sceneId: "",
        ruleName: "",
        // id:"",编辑的时候才有
        riskField: "",
        ruleType: "",
        cycleVal: "", // 频次周期
        thresholdVal: "", //频次阙值
        expressVal: "", //拼接正则表达式
        startIp: "", // 开始ip
        intervalVal: "", //区间值
        deductVal: 50,
        ruleRatio: 50,
      };
      this.endIp = "";
      if (sceneId) {
        // 风险场景新增规则，场景id已经自动绑定过来，需要携带
        this.vpnform.sceneId = sceneId + "";
      }
      this.$nextTick(() => {
        this.getsceneType(sceneId);
        this.$refs?.addform?.clearValidate();
      });
    },
    edit(row) {
      const {
        sceneId,
        ruleName,
        id, //编辑的时候才有
        riskField,
        ruleType,
        cycleVal, // 频次周期
        thresholdVal, // 频次阙值
        deductVal,
        ruleRatio,
        intervalVal,
      } = row;
      this.vpnform = {
        sceneId: sceneId + "",
        ruleName,
        id, //编辑的时候才有
        riskField: riskField + "",
        ruleType: ruleType + "",
        cycleVal, // 频次周期
        thresholdVal, // 频次阙值
        deductVal: Number(deductVal),
        ruleRatio: Number(ruleRatio) * 100,
        startIp: "",
        intervalVal: "",
      };
      if (intervalVal) {
        const arr = intervalVal.split(",");
        if (riskField == 0) {
          this.vpnform.startIp = arr[0] && arr[0];
          this.endIp = arr[1] && arr[1];
        } else {
          if (arr[0] && arr[1]) {
            this.vpnform.intervalVal = arr;
          } else {
            this.vpnform.intervalVal = "";
          }
        }
      } else {
        this.vpnform.startIp = "";
        this.endIp = "";
        this.vpnform.intervalVal = "";
      }
      this.getsceneType(sceneId);
      this.$refs?.addform?.clearValidate();
    },
    submitaddForm() {
      this.$refs["addform"].validate((val) => {
        if (val) {
          if (this.vpnform.riskField == "0") {
            this.vpnform.intervalVal = [this.vpnform.startIp, this.endIp];
          }
          const {
            sceneId,
            ruleName,
            id, //编辑的时候才有
            riskField,
            ruleType,
            cycleVal, // 频次周期
            thresholdVal, // 频次阙值
            deductVal,
            ruleRatio,
            intervalVal,
          } = this.vpnform;
          let qujianvalue = "";
          if (intervalVal.length > 0) {
            qujianvalue = intervalVal.join();
          }
          let params = {
            sceneId,
            ruleName,
            //id编辑的时候才有
            riskField,
            ruleType,
            cycleVal: cycleVal, // 频次周期
            thresholdVal: thresholdVal, // 频次阙值
            deductVal,
            ruleRatio: ruleRatio / 100,
            intervalVal: qujianvalue,
          };
          if (this.editFlag) {
            params.id = id;
            editList(params)
              .then((res) => {
                if (res.rescode == 200) {
                  this.$emit("update:dialogVisible1", false);
                  this.$message.success("编辑成功");
                  this.$emit("submit", 200);
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            // 调用新增接口
            addList(params)
              .then((res) => {
                if (res.rescode == 200) {
                  this.$emit("update:dialogVisible1", false);
                  this.$message.success("新增成功");
                  this.$emit("submit", 200);
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }
        }
      });
    },
    handleClose() {
      this.$emit("update:dialogVisible1", false);
    },
  },
  created() {
    this.getsceneList();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__content {
  .el-date-editor.el-input {
    width: 100%;
  }
}
::v-deep .el-button {
  .el-icon-edit + span {
    margin-left: 0px;
  }
  .el-icon-delete + span {
    margin-left: 0px;
  }
}
::v-deep .el-dialog {
  min-width: 640px;
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
  }
  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;
  }
}
.addDialog {
  .el-dialog {
    min-width: 640px;
  }

  .el-form {
    .el-form-item.slider {
      width: 100%;
    }
    ::v-deep.range {
      width: 100%;
      .el-form-item__content {
        display: flex;
        .timepicker {
          width: 100%;
        }
      }
    }
  }
}
</style>
